package logic

import (
	"context"
	"fmt"
	"github.com/pkg/errors"
	"zg2_zy/zy6_company/companyRpc/cache"
	"zg2_zy/zy6_company/companyRpc/models"
	"zg2_zy/zy6_company/companyRpc/pkg"

	"zg2_zy/zy6_company/companyRpc/company"
	"zg2_zy/zy6_company/companyRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *company.LoginRequest) (*company.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var ur models.User
	ur.Mobile = in.Mobile

	if err = ur.GetUserByMobile(); err != nil {
		return nil, errors.New("获取用户信息失败")
	}
	if ur.ID == 0 {
		if err = ur.Register(); err != nil {
			return nil, errors.New("注册失败")
		}
		sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
		if sms != in.SmsCode {
			return nil, fmt.Errorf("短信验证码错误")
		}
		ur.Mobile = in.Mobile
		ur.Password = pkg.Md5(in.Mobile)
		models.DB.Create(&ur)
	}

	if in.Password == "" {
		if in.SmsCode == "" {
			return nil, errors.New("短信验证码不能为空")
		}
		sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
		if sms != in.SmsCode {
			return nil, fmt.Errorf("短信验证码错误")
		}
	} else {
		if pkg.Md5(in.Password) != ur.Password {
			return nil, errors.New("密码错误")
		}
	}

	return &company.LoginResponse{
		Id: int64(ur.ID),
	}, nil
}
